<script setup lang="ts">
import { RefreshRight } from "@element-plus/icons-vue";
import { queryOrderPayStatus } from "~/api/order";
import { useOrderStore } from "~/store/useOrder";
import { useRoute } from "vue-router";
import { queryRiseStatus } from "~/api/goods";

// 声明全局QRCode类型
declare global {
  interface Window {
    QRCode: any;
  }
}

const orderStore = useOrderStore();
const emits = defineEmits(["close", "refreshQRCode", "paySuccess"]);
const props = defineProps({
  payData: {
    type: Object,
    required: true,
    default: () => {},
  },
});
const route = useRoute();

const close = () => {
  emits("close");
};

const qrcodeInstance = ref(null);
const expireTimeText = ref("");
const timer = ref();
const qrcodeLoading = ref(false);
const orderId = ref("");
const goodsId = ref("");
const type = ref("");

// URL格式验证和清理函数
const cleanUrl = (url) => {
  if (!url || typeof url !== 'string') {
    return '';
  }
  
  // 移除可能的HTML标签和特殊字符
  let cleanedUrl = url.trim();
  
  // 如果URL包含HTML表单内容（支付宝格式），提取action URL
  if (cleanedUrl.includes('<form') && cleanedUrl.includes('action=')) {
    console.log("检测到支付宝HTML表单格式");
    // 提取form的action属性中的URL
    const actionMatch = cleanedUrl.match(/action=["']([^"']+)["']/);
    if (actionMatch && actionMatch[1]) {
      cleanedUrl = actionMatch[1].trim();
      // 移除可能的反引号
      cleanedUrl = cleanedUrl.replace(/`/g, '');
      console.log("从HTML表单中提取的URL:", cleanedUrl);
    } else {
      console.warn("无法从HTML表单中提取action URL");
      return '';
    }
  }
  
  // 如果URL包含其他HTML内容，提取实际的支付链接
  if (cleanedUrl.includes('<!DOCTYPE html>') || cleanedUrl.includes('<html>')) {
    // 尝试从HTML中提取支付链接
    const urlMatch = cleanedUrl.match(/(?:weixin:\/\/|alipays:\/\/|https?:\/\/[^\s"'<>]+)/);
    if (urlMatch) {
      cleanedUrl = urlMatch[0];
    } else {
      console.warn("无法从HTML内容中提取有效的支付链接");
      return '';
    }
  }
  
  // 验证URL格式
  if (cleanedUrl.startsWith('weixin://') || 
      cleanedUrl.startsWith('alipays://') || 
      cleanedUrl.startsWith('https://') || 
      cleanedUrl.startsWith('http://')) {
    return cleanedUrl;
  }
  
  console.warn("URL格式不正确:", cleanedUrl);
  return '';
};

// 生成二维码的函数
const generateQRCode = () => {
  console.log("开始生成二维码...");
  console.log("payData:", props.payData);
  console.log("payType:", props.payData.payType);
  console.log("原始url:", props.payData.url);
  
  // 清理和验证URL
  const cleanedUrl = cleanUrl(props.payData.url);
  console.log("清理后的url:", cleanedUrl);
  
  // 支持微信和支付宝二维码生成
  if ((props.payData.payType === "weixin" || props.payData.payType === "alipay") && cleanedUrl) {
    console.log(`满足${props.payData.payType}支付条件，开始生成二维码`);
    
    // 清空之前的二维码
    const qrcodeElement = document.getElementById("qrcode");
    console.log("qrcode元素:", qrcodeElement);
    
    if (qrcodeElement) {
      qrcodeElement.innerHTML = "";
      console.log("已清空qrcode元素内容");
    }
    
    // 检查window对象和QRCode库
    console.log("window对象:", typeof window);
    console.log("window.QRCode:", window.QRCode);
    
    // 确保QRCode库已加载
    if (typeof window !== 'undefined' && window.QRCode) {
      console.log("QRCode库已加载，开始创建二维码");
      try {
        qrcodeInstance.value = new window.QRCode("qrcode", {
          text: cleanedUrl,
          width: 152,
          height: 152,
          colorDark: "#000",
          colorLight: "#fff",
          correctLevel: window.QRCode.CorrectLevel.H,
        });
        console.log("二维码创建成功:", qrcodeInstance.value);
      } catch (error) {
        console.error("生成二维码失败:", error);
        console.error("错误详情:", error.message);
        console.error("错误堆栈:", error.stack);
        
        // 如果生成失败，显示URL作为备用方案
        if (qrcodeElement) {
          qrcodeElement.innerHTML = `<div style="padding: 20px; text-align: center; word-break: break-all; font-size: 12px; color: #666;">二维码生成失败<br/>${cleanedUrl}</div>`;
        }
      }
    } else {
      console.error("QRCode库未加载");
      console.error("window类型:", typeof window);
      console.error("window.QRCode:", window.QRCode);
      
      // 尝试直接显示URL作为备用方案
      if (qrcodeElement) {
        qrcodeElement.innerHTML = `<div style="padding: 20px; text-align: center; word-break: break-all; font-size: 12px;">${cleanedUrl}</div>`;
      }
    }
  } else {
    console.log("不满足支付条件");
    console.log("payType:", props.payData.payType);
    console.log("payType是否为weixin:", props.payData.payType === "weixin");
    console.log("payType是否为alipay:", props.payData.payType === "alipay");
    console.log("清理后的url是否存在:", !!cleanedUrl);
    console.log("原始url是否存在:", !!props.payData.url);
  }
};

onMounted(() => {
  orderId.value = route.query.id as string;
  goodsId.value = route.query.gid as string;
  type.value = route.query.type as string;
  
  console.log("组件已挂载，开始检查QRCode库...");
  
  // 检查QRCode库是否已加载，如果没有则等待
  const checkQRCodeLibrary = () => {
    if (typeof window !== 'undefined' && window.QRCode) {
      console.log("QRCode库已加载，开始生成二维码");
      nextTick(() => {
        generateQRCode();
      });
    } else {
      console.log("QRCode库尚未加载，等待500ms后重试...");
      setTimeout(checkQRCodeLibrary, 500);
    }
  };
  
  // 开始检查QRCode库
  checkQRCodeLibrary();
  
  // 定时器，每秒更新一次过期时间
  timer.value = setInterval(() => {
    expireTimeText.value = expireTime();
  }, 1000);
  
  if (type.value === "j") {
    queryRiseOrderPayStatus();
  } else {
    queryPayStatus();
  }
});
// 支付二维码有效期转换，把"2024-10-27 00:02:45"转为几分几秒后过期，如果已过期显示"已过期"，并实时更新分和秒
const expireTime = () => {
  const now = new Date();
  const expire = new Date(props.payData.expireTime);
  const diff = expire.getTime() - now.getTime();
  const minutes = Math.floor(diff / 60000);
  const seconds = Math.floor((diff % 60000) / 1000);
  if (diff < 0) {
    return "已过期";
  }
  return `${minutes}分${seconds}秒`;
};
// 刷新二维码
const refreshQRCode = () => {
  emits("refreshQRCode");
};
// 卸载组件时清除定时器
const end = ref(false);
onUnmounted(() => {
  if (timer.value) clearInterval(timer.value);
  end.value = true;
});

// 轮询获取支付状态
const queryPayStatus = async () => {
  try {
    const statusRes = await queryOrderPayStatus({
      orderSn: orderStore.payInfo.orderSn,
    });
    if (statusRes.data && statusRes.data.status === 1) {
      emits("paySuccess");
    } else {
      if (!end.value) {
        setTimeout(() => {
          queryPayStatus();
        }, 3000);
      }
    }
  } catch (e) {
    console.log(e);
  }
};
// 轮询获取加价订单支付状态
const queryRiseOrderPayStatus = async () => {
  try {
    const statusRes = await queryRiseStatus({
      orderSn: orderId.value,
      goodsId: goodsId.value,
    });
    if (statusRes.data && statusRes.data.status === 1) {
      emits("paySuccess");
    } else {
      if (!end.value) {
        setTimeout(() => {
          queryRiseOrderPayStatus();
        }, 3000);
      }
    }
  } catch (e) {
    console.log(e);
  }
};
</script>

<template>
  <div class="success-dialog">
    <div class="dialog-content">
      <img class="close" src="~/assets/modal-close.png" alt="" @click="close" />
      <p class="title">
        请使用{{ payData.payType === "weixin" ? "微信" : "支付宝" }}扫码支付
      </p>
      
      <!-- 微信支付：使用 QRCode 生成二维码 -->
      <div id="qrcode" v-if="payData.payType === 'weixin'">
        <p v-if="expireTimeText === '已过期'" class="expire">已过期</p>
      </div>
      
      <!-- 支付宝支付：使用 iframe 展示 -->
      <div id="alipay" v-if="payData.payType === 'alipay'">
        <iframe
          class="pay-qrcode-ali"
          v-loading="qrcodeLoading"
          element-loading-text="加载中"
          :srcdoc="props.payData.url"
          frameborder="0"
          marginwidth="0"
          marginheight="0"
          scrolling="no"
          width="152"
          height="152"
        >
        </iframe>
        <p v-if="expireTimeText === '已过期'" class="expire">已过期</p>
      </div>
      <p class="tips">
        {{ expireTimeText === "已过期" ? "" : "距离二维码过期还剩" }}
        <span>{{ expireTimeText === "已过期" ? "" : expireTimeText }}</span>
      </p>
      <p class="refresh" @click="refreshQRCode">
        <el-icon><RefreshRight /></el-icon> 刷新
      </p>
    </div>
  </div>
</template>

<style scoped lang="scss">
.success-dialog {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: rgba(25, 30, 40, 0.4);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.dialog-content {
  width: 400px;
  background: #fff;
  border-radius: 16px 16px 16px 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 56px 59px 44px;
  box-sizing: border-box;
  position: relative;
  .close {
    width: 24px;
    height: 24px;
    position: absolute;
    top: 20px;
    right: 20px;
    cursor: pointer;
  }
  .title {
    color: #191e28;
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 8px;
  }
  .tips {
    color: rgba(25, 30, 40, 0.48);
    line-height: 24px;
    text-align: center;
    margin-bottom: 8px;
    span {
      color: #ff4f4f;
    }
  }
  .to-link {
    width: 102px;
    height: 36px;
    background: #1dbf73;
    border-radius: 8px 8px 8px 8px;
    text-align: center;
    line-height: 36px;
    color: #fff;
    text-decoration: none;
  }
}
.refresh {
  display: flex;
  align-items: center;
  color: #1dbf73;
  cursor: pointer;
}
.expire {
  color: #ff4f4f;
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 2;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 1);
}

#alipay {
  width: 172px;
  height: 172px;
  margin-bottom: 16px;
  border-radius: 16px;
  border: 1px solid #e5e5e5;
  padding: 10px;
  box-sizing: border-box;
  position: relative;
}
</style>

<style>
#qrcode {
  width: 172px;
  height: 172px;
  margin-bottom: 16px;
  border-radius: 16px;
  border: 1px solid #e5e5e5;
  padding: 10px;
  box-sizing: border-box;
  position: relative;
}
</style>
